package com.dhgate.spu.analysis.stat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.synonym.SolrSynonymParser;
import org.apache.lucene.analysis.synonym.SynonymFilter;
import org.apache.lucene.analysis.synonym.SynonymMap;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.util.Version;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dhgate.apsaras.access.ServiceProxyFactory;
import com.dhgate.prod.api.ProdService;
import com.dhgate.prod.dto.MapProductDTO;
import com.dhgate.spu.analysis.consts.SysConsts;
import com.dhgate.spu.analysis.dao.DAOFactory;
import com.dhgate.spu.analysis.init.InitDbConfig;

public class AttrMatchMain {
	private static final Logger log = LoggerFactory.getLogger(AttrMatchMain.class);
	public static void main(String[] args) throws Exception {
		
		//初始化基本配置参数
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File(SysConsts.CONST_PARAMXML_PATH));
		SysConsts.DAO_NAME = document.getRootElement().element("DAO").getTextTrim();
		System.out.println("DAO_NAME: "+SysConsts.DAO_NAME);
		//初始化数据来源
		DAOFactory.init();
		
		//读取数据库初始化配置
		InitDbConfig.init();
		
		System.out.println("数据库初始化完毕"); 
		
		System.out.println("============"+DAOFactory.getDAOInstance()+" ========"+DAOFactory.getDAOInstance().getAttrValMap("296289"));
		
		System.out.println("getAttrValMap(296289)获取完毕"); 
		
		//SpuStandardConsts.init();
		
		AttrMatchMain am = new AttrMatchMain();

		String cateId = "002009002";
		String sourcePath = "/spu/tianweilin/spu-analysis_1/002009002.csv";     
		String targetPath = "/spu/tianweilin/spu-analysis_1/002009002_ok.csv"; 
		
		am.putRequiredAttrVal(cateId,sourcePath,targetPath);									
	}
	
	/**
	 * 读取csv，选择合适属性值回填到csv
	 * @param sourcePath  csv源路径
	 * @param targetPath  输出路径
	 */
	public void putRequiredAttrVal(String cateId,String sourcePath,String targetPath){
        BufferedReader br = null;
        String sCurrentLine;
        try {
			br = new BufferedReader(new FileReader(sourcePath));
			while((sCurrentLine = br.readLine()) != null){
				int index = sCurrentLine.indexOf(",");
				sCurrentLine = sCurrentLine.substring(index+1);
	            System.out.println(sCurrentLine);
	            String[] split = sCurrentLine.split(",");
	            
	            //解决由于“，”分隔符引起的错误
	            int specialIndex = 0;
	            for(int i = 0;i < split.length;i++){
	            	if(split[i].indexOf("\"") != -1){
	            		specialIndex = i;
	            	}
	            } 
	            if(specialIndex != 0){
	            	for(int i=2;i <= specialIndex;i++){
	            		split[1] += " "+split[i]+" ";
	            	}
	            	
	            	split[4] = split[specialIndex + 3];
	            }
	            System.out.println();
	                        		            	
	            	//写数据
	            	String requiredAttrAppend = ","+" "+","+" "+","+"N"; 
	                FileWriter fw = new FileWriter(targetPath,true);//append true -->>new FileWrite(file,true);
	                BufferedWriter bw = new BufferedWriter(fw);
	                try {
	                	boolean isChildAttr = isChildAttr(split[4]); //是否子属性
	                	
	                	boolean flag= true; //是否开启二级属性级联
	                	if(!isChildAttr || flag){
	                		requiredAttrAppend = putAppendString(cateId,split[1], split[4]);
	                	}else{//子属性
	                		//查找到父属性
	                		String parentAttrId = getParentAttr(split[4]);
	                		//匹配出父属性值List、取父属性的 id、当前子属性id，获得属性值组，匹配出结果
	                		Map<String, String> parentAttrvalMap = getParentMatchMap(cateId,split[1], parentAttrId);//TODO  一级属性不为空，parentAttrvalMap
	                		String attrType = getAttrType(split[4]);
	                		String requiredTemp = "";
	                		for(String s:parentAttrvalMap.keySet()){
	                			Map<String, String> attrValGroup = queryAttrValGroup(split[4], s);
	                			
	                			for(String as:attrValGroup.keySet()){
	                				String aV = attrValGroup.get(as);
	                				boolean cIsRequired = isRequiredAttrVal(split[1], aV);
	                				if(cIsRequired){
	                					requiredTemp += ","+attrValGroup.get(as)+","+as+","+"Y";
	                					requiredAttrAppend = ","+attrValGroup.get(as)+","+as+","+"Y";
	                					if(!"1".endsWith(attrType)){
	                						break;
	                					}
	                				}	                				
	                			}
	                		}
	                		if(!StringUtils.isBlank(requiredTemp)){
	                			requiredAttrAppend = requiredTemp;
	                		}
	                		requiredAttrAppend += ","+"Level 2";
	                	}

						
					} catch (ParseException e) {
						requiredAttrAppend = ","+" "+","+" "+","+"Exception";
						e.printStackTrace();
					}
	                
	                //多行属性另起一行
	                int attrTime = getCharTime(requiredAttrAppend, "Y");
	                if(attrTime > 1){
	                	String[] nodes = requiredAttrAppend.split(",");
	        			for(int i = 1;i < nodes.length;i=i+3){
	        				String sTemp = ","+nodes[i]+","+nodes[i+1]+","+nodes[i+2];
	        				bw.write(sCurrentLine+sTemp+"\n"); 	
	        				bw.flush();
	        			}
	                }else if(attrTime==1){
	                	bw.write(sCurrentLine+requiredAttrAppend+"\n"); 	 
	                	bw.flush();
	                }else{
	                	bw.write(sCurrentLine+requiredAttrAppend+"\n"); 	 
	                	bw.flush();
	                }	                
	                               	                
	                
	                bw.close();
	            		            
	        }
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}		
		
	}
	

	/**
	 * 判断属性是否是需要回填的数据
	 * @param title   产品标题
	 * @param attrVal   回填属性值
	 * @return
	 */
	public boolean isRequiredAttrVal(String title,String attrVal) throws IOException, ParseException{
		boolean isRequiredAttrVal = false;
		boolean dedup = true;
		boolean expand = false;
		

		
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43);
		SolrSynonymParser parser = new SolrSynonymParser(dedup, expand, analyzer);

		parser.add(new FileReader(new File(SysConsts.CONST_SYNOYM_FILE_PATH)));
		SynonymMap build = parser.build();
		
		StringReader reader = new StringReader(title);
		TokenStream ts = analyzer.tokenStream("", reader);

		SynonymFilter synonymFilter = new SynonymFilter(ts, build, true);
		CharTermAttribute term = synonymFilter.getAttribute(CharTermAttribute.class);
		synonymFilter.reset();
		//002001001 特殊处理
		if("Split Front/Side".equals(attrVal)){
			attrVal = "split front";
		}
		title = title.toLowerCase().replaceAll("high neck", "high collar");
		
		//多词语比对
		String a[] = attrVal.split(" ");
		String attrValTemp = "";
		if(a.length < 2){
			a = attrVal.split("-");
		}
		if(a.length < 2){
			a = attrVal.split("/");
		}	
		if(a.length > 1){
			for(int i = 0;i < a.length;i++){
				attrValTemp = attrValTemp + a[i]+" ";
			}
			attrVal = attrValTemp;
		}
		StringBuilder rString = new StringBuilder();
		while (synonymFilter.incrementToken()) {
			if(term.toString().equals(attrVal.toLowerCase())){
				isRequiredAttrVal = true;
			}
			rString.append(term.toString()+" ");
		}
		if(a.length > 1 && (rString.indexOf(attrVal.toLowerCase()) != -1 ||title.toLowerCase().indexOf(attrVal.toLowerCase()) != -1)){
			isRequiredAttrVal = true;
		}
		return isRequiredAttrVal;
	}		

	/**
	 * 获取AttrMap
	 * @param attrId  attrId
	 * @return key:attrValId   value:attrValName
	 */
	public Map<String, String> getAttrvalList(String cateId,String attrId){

		Map<String, String> attrValMap = DAOFactory.getDAOInstance().getAttrValMap(cateId,attrId);
		log.info(attrId);
		return attrValMap;
	}
	
	// 缺失的属性是否子属性
	public boolean isChildAttr(String attrId){
		
		return DAOFactory.getDAOInstance().isChildAttr(attrId);
		
		
	}
	
	//　二级属性获取 其父属性
	public String getParentAttr(String attrId){
		return DAOFactory.getDAOInstance().getParentAttr(attrId);
	}
	
	//TODO 通过父属性调用getProductAttrList查询该商品属性列表
	public void queryProductAttrList(String attrId){
		//public MapProductDTO getMapProductDTO(Long itemcode);  得到supplierid
		//public List<ProductAttrDTO> getProductAttrList(String supplierid,ProductAttrDTO qdto)  查询商品属性列表

	}
	
	public void getSupplierid(Long itemcode){
		ProdService prodService = ServiceProxyFactory.getServiceProxy(ProdService.class,"2.0.5");
		MapProductDTO mapProductDTO = prodService.getMapProductDTO(itemcode);
	}
	
	// 查询到属性值列表，列表内查询到属性值组，判断该属性属于多选还是单选，赋值上属性值
	public Map<String, String> queryAttrValGroup(String childAttrId,String parentAttrValId){
		return DAOFactory.getDAOInstance().getAttrvalGroupMap(childAttrId, parentAttrValId);
	}
	
	// 判断属于单选还是多选 1：多选   2：单选
	public String getAttrType(String attrId){
		return DAOFactory.getDAOInstance().getAttrType(attrId);
	}
	
	
	private String putAppendString(String cateId,String title,String attrId) throws IOException, ParseException{
		String requiredAttrAppend = "";
    	Map<String, String> attrvalMap = getAttrvalList(cateId,attrId); //split[4]:attrId
    	
    	//attrvalMap排序
    	List<Entry<String, String>> sortList = sortMap(attrvalMap);
    	
    	String attrType = getAttrType(attrId);
    	if(attrvalMap != null){
    		String attrAppendTemp = null;
    		for(Entry<String, String> L:sortList){
    			boolean isRequiredAttrVal = isRequiredAttrVal(title,L.getValue());//split[1]:标题    
    			if(isRequiredAttrVal){
    				attrAppendTemp +=  ","+L.getValue()+","+L.getKey()+","+"Y";
    				requiredAttrAppend = ","+L.getValue()+","+L.getKey()+","+"Y";
    				if(!"1".equals(attrType)){
    					break;
    				}
    				
    			}else{
    				requiredAttrAppend = ","+" "+","+" "+","+"N";
    			}
    		}
    		if(!StringUtils.isBlank(attrAppendTemp)){
    			requiredAttrAppend = attrAppendTemp;
    		}
    		
    	}else{
    		requiredAttrAppend = ","+" "+","+" "+","+"N";
    	}	
    	return requiredAttrAppend;
	}
	
	//获取子属性的父属性匹配出的Map
	public Map<String, String> getParentMatchMap(String cateId,String title,String parentAttrId) throws IOException, ParseException{
		String requiredAttrAppend = "";
		Map<String, String> map = new HashMap<String, String>();
    	Map<String, String> attrvalMap = getAttrvalList(cateId,parentAttrId); //split[4]:attrId
    	String attrType = getAttrType(parentAttrId);
    	if(attrvalMap != null){
    		String attrAppendTemp = null;
    		for(String s:attrvalMap.keySet()){
    			boolean isRequiredAttrVal = isRequiredAttrVal(title,attrvalMap.get(s));//split[1]:标题    
    			if(isRequiredAttrVal){
    				attrAppendTemp +=  ","+attrvalMap.get(s)+","+s+","+"Y";
    				requiredAttrAppend = ","+attrvalMap.get(s)+","+s+","+"Y";
    				map.put(s, attrvalMap.get(s));
    				if(!"1".equals(attrType)){
    					break;
    				}
    				
    			}else{
    				requiredAttrAppend = ","+" "+","+" "+","+"N";
    			}
    		}
    		if(!StringUtils.isBlank(attrAppendTemp)){
    			requiredAttrAppend = attrAppendTemp;
    		}
    		
    	}else{
    		requiredAttrAppend = ","+" "+","+" "+","+"N";
    	}	
    	return map;
	}


	//字符出现次数
	public  int getCharTime(String source,String s){
		if(source.indexOf(s) == -1){
			return 0;
		}
		int count = 0;
		for(int i = 0;i < source.length();i++){
			if(s.equals(String.valueOf(source.charAt(i)))){
				count ++;
			}
		}
		return count;
	}


	/**
	 * map 排序
	 * @param map
	 * @return
	 */
	public static  List<Map.Entry<String,String>> sortMap(Map<String, String> map){
		  List<Map.Entry<String,String>> mappingList = null; 
	  
		  //通过ArrayList构造函数把map.entrySet()转换成list 
		  mappingList = new ArrayList<Map.Entry<String,String>>(map.entrySet()); 
		  //通过比较器实现比较排序 
		  Collections.sort(mappingList, new Comparator<Map.Entry<String,String>>(){ 
		   public int compare(Map.Entry<String,String> mapping2,Map.Entry<String,String> mapping1){ 
		    return mapping1.getValue().length()-(mapping2.getValue().length()); 
		   } 
		  }); 		  			
			  
		return mappingList;
	}
	
}
